﻿using NineSeas.Models;
using NineSeas.Services;
using System.Linq;
using Orchard;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Handlers;
using Orchard.Data;

namespace NineSeas.Handlers
{
    public class BookPartHandler: ContentHandler
    {
        public BookPartHandler(IRepository<BookPartRecord> repository,
            IRepository<ChapterPartRecord> chapterRepository,
            IChapterService chapterService,
            IOrchardServices services)
        {
            Filters.Add(StorageFilter.For(repository));

            OnPublished<BookPart>((context, part) => {
                if (part.BookType == BookTypeEnum.Text)
                {
                    var chapters = services.ContentManager.Query<ChapterPart, ChapterPartRecord>()
                            .ForVersion(VersionOptions.Latest)
                            .Where(c => c.BookId == part.Id)
                            .List();

                    foreach (var chapter in chapters)
                    {
                        if (!chapter.ContentItem.VersionRecord.Published)
                        {
                            services.ContentManager.Publish(chapter.ContentItem);
                        }
                    }
                }

                // update the number of books for the author
                var profile = services.ContentManager.Get<AuthorProfilePart>(part.AuthorId);
                if (profile != null)
                {
                    profile.BookCount = repository.Count(b => b.AuthorId == profile.Id && b.ContentItemVersionRecord.Published
                        && chapterRepository.Table.Any(c => c.BookId == b.ContentItemRecord.Id && c.ContentItemVersionRecord.Published));
                }
            });
        }
    }
}